﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager : MonoBehaviour
{
    private Dictionary<string, GameObject> m_UI       = new Dictionary<string, GameObject>();
    private Dictionary<string, Transform>  m_UIGroups = new Dictionary<string, Transform>();
    private Transform m_UIParent;

    private void Awake()
    {
        m_UIParent = this.transform.parent.Find("UI");
    }

    private Transform GetUIGroup(string group)
    {
        if (!m_UIGroups[group])
            Debug.LogError("UIGroup is not exists");
        return m_UIGroups[group];
    }

    public void SetUIGroup(List<string> groups)
    {
        for (int i = 0; i < groups.Count; i++)
        {
            GameObject group = new GameObject("UIGroup-" + groups[i]);
            group.transform.SetParent(m_UIParent, false);
            m_UIGroups[groups[i]] = group.transform;
        }
    }

    //Lua调用
    public void OpenUI(string uiName,string uiGroup,string luaName)
    {
        //已被加载
        GameObject ui = null;
        if (m_UI.TryGetValue(uiName,out ui))
        {
            UILogicBehaviour uILogic=ui.GetComponent<UILogicBehaviour>();
            uILogic.OnUIOpen();
            return;
        }

        //未被加载
        Manager.ResourceManager.LoadUI(uiName,(UnityEngine.Object obj) =>
        {
            GameObject ui2 =Instantiate(obj) as GameObject;
            m_UI.Add(uiName, ui2);

            Transform parent = GetUIGroup(uiGroup);
            Debug.Log(uiGroup);
            ui2.transform.SetParent(parent, false);

            //为UI对象添加组件
            UILogicBehaviour uiLogic= ui2.AddComponent<UILogicBehaviour>();
            uiLogic.Init(luaName);
            uiLogic.OnUIOpen();
        });
    }
}
